﻿using System;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IntellectShop.Common;
using IntellectShop.Web2.ViewModels;

namespace IntellectShop.Web2.Controllers
{
	[IntellectShop.Web2.Code.NoCache]
	[IntellectShop.Web2.Code.HandleErrorWithELMAH]
	[ValidateInputAttribute(false)]
	public class OrderController : Controller
	{
		const int CountLatestOrder = 4;

		//
		// GET: /Order/
		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Index()
		{
			var orders = Common.Order.RetrieveAll();
			return View(orders);
		}

		//
		// GET: /Order/Details/5
		[Authorize]
		public ActionResult Details(int orderID)
		{
			var order = HttpContext.User.IsInRole(Globals.AdministratorRoleName) ?
				Common.Order.RetrieveByID(orderID, null) :
				Common.Order.RetrieveByID(orderID, HttpContext.User.Identity.Name);
			return View(order);
		}

		//
		// GET: /Order/Create
		[Authorize]
		public ActionResult Create()
		{
			var viewModel = new OrderEditViewModel
			{
				Order = Common.Order.CreateLikeLast(HttpContext)
			};

			return View(viewModel);
		}

		[Authorize]
		[HttpPost]
		public ActionResult Create(Common.Order order)
		{
			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: Order!");

				Common.Cart cart = Common.Cart.CreateCart(HttpContext);
				cart.CartItems = cart.GetCartItems();
				order.OrderOwnerID = cart.CartOwnerID;

				string createdBy = HttpContext.User.Identity.Name;
				order.Create(cart, createdBy);
				this.SendNotificationMail(Common.Order.RetrieveByID(order.OrderID, null));
				return RedirectToAction("Details", new { orderID = order.OrderID });
			}
			catch (Exception e)
			{
				var viewModel = new OrderEditViewModel
				{
					Order = Common.Order.CreateLikeLast(HttpContext),
					Message = e.Message
				};

				return View(viewModel);
			}
		}

		private void SendNotificationMail(Common.Order order)
		{
			string storeEmail = ConfigurationManager.AppSettings["StoreEmail"];
			string managerEmail = ConfigurationManager.AppSettings["ManagerEmail"];
			string forceUsePickupDirectory = ConfigurationManager.AppSettings["ForceUsePickupDirectory"];
			if (!String.IsNullOrEmpty(forceUsePickupDirectory))
			{
				forceUsePickupDirectory = Server.MapPath(forceUsePickupDirectory);
			}

			var clientEmails = MailUtils.GetEmals(order.Email);
			MailUtils.Send(
				storeEmail,
				clientEmails.Count > 0 ? clientEmails.First() : "",
				Server.MapPath("~/App_Data/MailTemplates/template.htm"),
				"windows-1251",
				order.Print(),
				order.DisplayName,
				forceUsePickupDirectory,
				managerEmail);
		}

		//
		// GET: /Order/Edit/5
		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Edit(int orderID)
		{
			var viewModel = new OrderEditViewModel
			{
				Order = Common.Order.RetrieveByID(orderID, null)
			};

			return View(viewModel);
		}

		//
		// POST: /Order/Edit/5
		[Authorize(Roles = Globals.AdministratorRoleName)]
		[HttpPost]
		public ActionResult Edit(int orderID, FormCollection collection)
		{
			var order = Common.Order.RetrieveByID(orderID, null);
			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: Order!");

				UpdateModel(order, "Order");
				order.Update(HttpContext.User.Identity.Name);
				return RedirectToAction("Details", new { orderID = order.OrderID });
			}
			catch(Exception e)
			{
				var viewModel = new OrderEditViewModel
				{
					Order = Common.Order.RetrieveByID(orderID, null),
					Message = e.Message
				};

				return View(viewModel);
			}
		}

		////
		//// GET: /Order/Delete/5
		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Delete(int orderID)
		{
			var order = Common.Order.RetrieveByID(orderID, null);
			if (order == null)
				throw new HttpException(404, "Page not found");

			return View(new OrderRemoveViewModel { Order = order });
		}

		////
		//// POST: /Order/Delete/5
		[Authorize(Roles = Globals.AdministratorRoleName)]
		[HttpPost]
		public ActionResult Delete(int orderID, FormCollection collection)
		{
			var order = Common.Order.RetrieveByID(orderID, null);
			if (order == null)
				throw new HttpException(404, "Page not found");

			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: Order!");

				Common.Order.Delete(orderID);
				return RedirectToAction("Index");
			}
			catch (Exception e)
			{
				var viewModel = new OrderRemoveViewModel
				{
					Order = order,
					Message = e.Message
				};
				return View(viewModel);
			}
		}
	}
}
